<?php
header('Content-Type: application/json');
Header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE');
header("Access-Control-Allow-Headers: Content-Type");
header('Access-Control-Allow-Origin:*');   //跨域

require './send_email_init.php';
require './get_captcha_init.php';
require './mysql_init.php';

//判断是否注册过
function is_register($pdo, $register_email) {
    try {
        // 准备查询语句
        $query = "SELECT COUNT(*) FROM users WHERE email = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $register_email);
        // 执行查询
        $statement->execute();
        // 获取结果
        $count = $statement->fetch()["COUNT(*)"];      //把查询结构赋值给$count
        // 根据结果判断是否存在
        if ($count > 0) {
            return false; // 存在
        } else {
            return true; // 不存在
        }
    } catch (PDOException $e) {
        // 异常处理
        echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//获取当前时间,字符串形式
function get_time(){
    date_default_timezone_set("PRC");     //设置时区，PRC是中国人民共和国
    return date("Y-m-d H:i:s",time());  //以参数1的格式输出参数2，参数2是时间戳格式，参数1见格式表
}
//把邮箱，验证码，验证码时间保存到临时注册表里
function insertData($pdo, $email, $captcha, $captcha_time) {
    try {
        // 准备插入语句并绑定参数
        $query = "INSERT INTO register(register_email,captcha_register_email,captcha_register_email_time) values(:email, :captcha, :captcha_time)";
        $statement = $pdo->prepare($query);
        $statement->bindParam(":email", $email);
        $statement->bindParam(":captcha", $captcha);
        $statement->bindParam(":captcha_time", $captcha_time);
        
        // 执行插入操作
        $statement->execute();
        
        // echo "Data inserted successfully.";
    } catch (PDOException $e) {
        echo "Error inserting data: " . $e->getMessage();
    }
}
//获取验证码次数和上一次时间
function get_register_captcha_n($pdo, $register_email) {
    try {
        // 准备查询语句
        $query = "SELECT captcha_register_email_time,n FROM register WHERE register_email = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $register_email);
        // 执行查询
        $statement->execute();
        // 获取结果
        // $count = $statement->fetchAll()[0]["n"];      //把查询结构赋值给$count
        $n_time=$statement->fetchAll()[0];      //把查询结构赋值给$count

        return $n_time;
    } catch (PDOException $e) {
        // 异常处理
        echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//输入字符串时间，返回字符串时间与当前时间的差
function getTimeDifferenceInSeconds($strTime) {
    // 字符串时间转换为时间戳
    $timestamp = strtotime($strTime);

    date_default_timezone_set("PRC");     //设置时区，PRC是中国人民共和国
    
    // 获取当前时间戳
    $currentTimestamp = time();
    
    // 计算时间差
    $timeDiff = $currentTimestamp-$timestamp;
    
    // 返回时间差（秒）
    return $timeDiff;
}
//把邮箱，验证码，验证码时间更新到临时注册表里
function updateData($pdo, $email, $captcha, $captcha_time,$n) {
    try {
        // 准备插入语句并绑定参数
        $query = "UPDATE register set captcha_register_email=?,captcha_register_email_time=?,n=? where register_email=?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(3, $n);
        $statement->bindParam(1, $captcha);
        $statement->bindParam(2, $captcha_time);
        $statement->bindParam(4, $email);
        
        // 执行插入操作
        $statement->execute();
        
        // echo "Data inserted successfully.";
    } catch (PDOException $e) {
        echo "Error updata data: " . $e->getMessage();
    }
}
//判断预注册表中有没有此邮箱
function panduan_yu_register($pdo, $register_email){
    try {
        // 准备查询语句
        $query = "SELECT COUNT(*) FROM register WHERE register_email = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $register_email);
        // 执行查询
        $statement->execute();
        // 获取结果
        $count = $statement->fetch()["COUNT(*)"];      //把查询结构赋值给$count
        // 根据结果判断是否存在
        if ($count > 0) {
            return true; // 存在
        } else {
            return false; // 不存在
        }
    } catch (PDOException $e) {
        // 异常处理
        echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
};
//判断post的数据类型是否有异常
function is_str($register_email){
    $flag=true;
    if(gettype($register_email)!=="string"){
        $flag=false;
    }
    if(!isEmail($register_email)){
        $flag=false;
    }
    return $flag;
}
//判断是否是邮箱
function isEmail($email) {
    // 邮箱地址的正则表达式
    $pattern = "/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/";
    
    // 使用preg_match函数进行匹配
    if (preg_match($pattern, $email)) {
        return true; // 符合邮箱格式
    } else {
        return false; // 不符合邮箱格式
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {      //判断是否是post请求
    $response = array(
        'status' => 0,
        'message' => 'sending'
    );

    $json=file_get_contents('php://input');  //获取post请求中的原始数据
    $post_json=json_decode($json,true);       //把原始数据转化成json
    $register_email=$post_json['register_email'];   //获取邮箱

    if(is_str($register_email)){     //邮箱格式正确
        if(is_register($pdo, $register_email)){        //判断邮箱是否注册过
            if(panduan_yu_register($pdo, $register_email)){     //判断是否预注册过
                $arr=get_register_captcha_n($pdo, $register_email);    //获取上一次验证码时间，次数
                if($arr['n']<=2){               //判断获取验证码次数
                    $captcha=get_captcha(4);

                    $send_out_email='2183180991@qq.com';      //发件人邮箱
                    $send_out_email_pwd='srnymnubqeaoebdd';    //发件人邮箱密码(授权码)
                    $send_count='您的验证码为 '.$captcha.',若非本人操作请忽略此消息';    //要发送的消息
                    $nickname='诺言非';                                        //发件人对外的昵称
                    $receive_email=$register_email;                          //收件人邮箱

                    send_to_email($send_out_email,$send_out_email_pwd,$send_count,$nickname,$receive_email);

                    $email=$register_email;
                    $captcha_time=get_time();
                    $n=$arr['n']+1;
                    updateData($pdo, $email, $captcha, $captcha_time,$n);     //更新验证码，时间，次数
                    $response = array(
                        'status' => 1,
                        'message' => '验证码次数未达5次',
                    );
                }else if($arr['n'] > 2 && getTimeDifferenceInSeconds($arr['captcha_register_email_time']) > 60){    //判断获取验证码次数和距离上一次时间
                    $captcha=get_captcha(4);
    
                    $send_out_email='2183180991@qq.com';      //发件人邮箱
                    $send_out_email_pwd='srnymnubqeaoebdd';    //发件人邮箱密码(授权码)
                    $send_count='您的验证码为 '.$captcha.',若非本人操作请忽略此消息';    //要发送的消息
                    $nickname='诺言非';                                        //发件人对外的昵称
                    $receive_email=$register_email;                          //收件人邮箱
    
                    send_to_email($send_out_email,$send_out_email_pwd,$send_count,$nickname,$receive_email);
    
                    $email=$register_email;
                    $captcha_time=get_time();
                    $n=0;
                    updateData($pdo, $email, $captcha, $captcha_time,$n);    //刷新次数
                    $response = array(
                        'status' => 1,
                        'message' => '重置次数',
                    );
                }else{             //频繁
                    $response = array(
                        'status' => 0,
                        'message' => '发送验证码频繁',
                    );
                } 
            }else{               //第一次预注册
                $captcha=get_captcha(4);

                $send_out_email='2183180991@qq.com';      //发件人邮箱
                $send_out_email_pwd='srnymnubqeaoebdd';    //发件人邮箱密码(授权码)
                $send_count='您的验证码为 '.$captcha.',若非本人操作请忽略此消息';    //要发送的消息
                $nickname='诺言非';                                        //发件人对外的昵称
                $receive_email=$register_email;                          //收件人邮箱

                send_to_email($send_out_email,$send_out_email_pwd,$send_count,$nickname,$receive_email);    //发送邮件

                $email=$register_email;
                $captcha_time=get_time();
                insertData($pdo, $email, $captcha, $captcha_time);       //把邮箱，验证码，时间插入到临时注册表里
                $response = array(
                    'status' => 1,
                    'message' => '第一次预注册成功',
                );
            }
        }else{       //已注册
            $response = array(
                'status' => 0,
                'message' => '已注册过'
            );
        }
    }else{     //邮箱格式错误
        $response = array(
            'status' => 0,
            'message' => '邮箱格式错误'
        );
    }
    echo json_encode($response);
} else{             //如果不是post请求
    $response = array(
        'status' => 0,
        'message' => '错误请求'
    );
    echo json_encode($response);
}
?>